<template>
	<div class="takecash">
		<p class="takecash-title">缴费办理</p>
		<!-- 处理缴费表单 -->
		<el-form :model="takecash" :rules="rules" ref="takecashForm" label-width="100px" class="takecash-ruleForm">
			<el-form-item label="需缴费患者">
				<el-select clearable class="filter-item" style="width: 130px" placeholder="患者信息"
					v-model="patientInformation" @change="handleSelectChange">
					<el-option v-for="item in patientList" :key="item.number" :label="item.name+' '+item.number"
						:value="item.number">
					</el-option>
				</el-select>
			</el-form-item>
			<div v-show="takecash.prescript_number!=null && takecash.prescript_number!=''">
				<el-form-item label="患者姓名">
					{{takecash.patientName}}
				</el-form-item>
				<el-form-item label="处理编号">
					{{takecash.prescript_number}}
				</el-form-item>
				<el-form-item label="身份证号">
					{{takecash.idCard}}
				</el-form-item>
			</div>
			<hr />

			<!-- 下面实时监听number的值，找到该值的话就会赋值给isShow，这样isShow也是实时变化的了 -->
			<!-- 如果找到输入的处方编号就把处方的药品数据展示出来，否则隐藏数据表格-->
			<template v-if="number === isShow && number !== ''">
				<el-table :data="takecash.prescription">
					<el-table-column prop="sort" label="药品分类">
					</el-table-column>
					<el-table-column prop="drugname" label="药品名称">
					</el-table-column>
					<el-table-column prop="quantity" label="用量（件/克）">
					</el-table-column>
					<el-table-column prop="usage" label="用法">
					</el-table-column>
				</el-table>
			</template>
			<template v-else>
			</template>
			<p class="takecash_p">
				<el-form-item label="应收金额（元）：" class="shouldMoney" label-width="100">
					<span v-show="showMoney" class="money">{{ takecash.shouldMoney }}</span>
				</el-form-item>
				<el-button type="primary" class="computeBtn" @click="compute()">计算应收金额</el-button>
			</p>
			<el-form-item label="实收金额（元）：" prop="exactMoney" class="exactMoney" label-width="80">
				<el-input v-model="takecash.exactMoney" style="width: 75%"></el-input>
			</el-form-item>
			<p class="takecash_p">
				<el-form-item label="找零（元）：" class="theChange" label-width="100">
					<span v-show="showChange" class="money">{{takecash.theChange}}</span>
				</el-form-item>
				<el-button type="primary" class="changeBtn" @click="change()">计算找零</el-button>
			</p>
			<el-button type="reset" @click="resetForm('takecashForm')" class="reset">重置</el-button>
			<el-button type="primary" @click="handleDownload"><i
					class="el-icon-document el-icon--left"></i>打印</el-button>
		</el-form>
	</div>
</template>

<script type="text/ecmascript-6">
	import {
		api
	} from '../../../global/api.js';
	import Vue from 'vue';
	export default {
		data() {
			// 验证患者姓名是否存在的方法

			let checkName = (rule, value, callback) => {

				let b = true
				for (let k = 0; k < this.patients.length; k++) {
					if (value == this.patients[k].name) {
						b = false
						break;
					}
				}
				if (b) {
					callback(new Error('无此患者姓名！'));
				} else {
					callback();
				}
			};


			// 验证处方是否存在的方法
			let checkPrescription = (rule, value, callback) => {
				let b = true
				for (let k = 0; k < this.patients.length; k++) {
					if (value == this.patients[k].number) {
						b = false
						break;
					}
				}
				if (b) {
					callback(new Error('无此处方！'));
				} else {
					callback();
				}
			};
			// 验证患者身份证号是否与输入的姓名对应以及格式是否正确的方法
			let checkCertificate = (rule, value, callback) => {
				let b = true
				if (/^\d+$/.test(value) !== false) {
					if (value.length !== 18) {
						callback(new Error('身份证号应为18位数！'));
					} else {
						for (let k = 0; k < this.patients.length; k++) {
							if (value == this.patients[k].idCard) {
								b = false
								break;
							}
						}
						if (b) {
							callback(new Error('身份证号与姓名不对应！'));
						} else {
							callback();
						}
					}
				} else {
					callback(new Error('请输入数字值！'));
				}
			};
			return {
				takecash: {
					patientName: '',
					idCard: '',
					prescript_number: '',
					prescription: [],
					shouldMoney: 0,
					exactMoney: 0,
					theChange: 0
				},
				number: '', // 处方编号 （被监听）
				isShow: '', // 存放处方编号在被监听的过程中的最终值
				showMoney: false,
				showChange: true,
				copy: [], //打印数据
				patientInformation: '', // 选择的患者处方编号
				patientList: [], // 所有患者的信息
				rules: {
					patientName: [{
						required: true,
						validator: checkName,
						trigger: 'blur'
					}],
					idCard: [{
						required: true,
						validator: checkCertificate,
						trigger: 'blur'
					}],
					prescript_number: [{
						required: true,
						validator: checkPrescription,
						trigger: 'blur'
					}],
				}
			};
		},
		methods: {
			// 计算应收金额
			compute() {
				this.showMoney = true;
				this.$refs.takecashForm.validate((valid) => {
					if (!valid) {
						this.$notify.error({
							message: '请检查所有的必要信息填写！'
						});
					} else {
						let that = this;
						let apilogin = "http://localhost:8088/findPrescriptionByPatientNumberAndSun/" + this.number
						this.$http.get(apilogin).then((response) => {
							that.takecash.shouldMoney = response.body.data.price;
							that.takecash.shouldMoney = parseFloat(that.takecash.shouldMoney.toFixed(0));
						}, response => {
							this.$message({
								message: '数据请求失败',
								type: 'error'
							});
						});
					}
				});
			},
			// 重置
			resetForm(formName) {
				this.$refs.takecashForm.resetFields();
				this.isShow = '';
				this.number = '';
				this.showMoney = false;
				this.showChange = false;
			},
			// 找零
			change() {
				let that = this;
				if (this.takecash.exactMoney > this.takecash.shouldMoney) {

					that.takecash.theChange = parseFloat((that.takecash.exactMoney - that.takecash.shouldMoney).toFixed(
					2));


					let apilogin = "http://localhost:8088/selectPrescriptionByNumber/" + this.number + "/" + this.takecash
						.shouldMoney
					this.$http.get(apilogin).then((response) => {
						that.copy = response.body.data.printBills;
					}, response => {
						this.$message({
							message: '数据请求失败',
							type: 'error'
						});
					});
				} else {
					this.$message({
						message: '支付金额不足',
						type: 'error'
					});

				}


			},
			/**
			 * 导出表格数据为Excel文件
			 * 使用Export2Excel插件将数据转换为excel格式并下载
			 * @method handleDownload
			 * @description 将表格数据导出为Excel文件,包含以下列:名字、性别、主治医生、药品名称、使用方法、药品类型、价格
			 * @returns {void} 无返回值,直接触发文件下载
			 */
			handleDownload() {
				const {
					export_json_to_excel
				} = require('vendor/Export2Excel');
				const tHeader = ['名字', '性别', '主治医生', '药品名称', '使用方法', '药品类型', '价格', '总价'];
				const filterVal = ['name', 'sex', 'doctor', 'drugName', 'usage', 'type', 'price', 'priceAll'];
				const data = this.formatJson(filterVal, this.copy);
				export_json_to_excel(tHeader, data, '发票');
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]));
			},
			handleSelectChange(patientInformation) {
				const form = this.patientList.find(nurse => nurse.number === patientInformation);
				if (form) {
					this.takecash = {
						patientName: form.name,
						idCard: form.idCard,
						prescript_number: form.number,
						prescription: [],
						shouldMoney: 0,
						exactMoney: 0,
						theChange: 0
					};
					this.number = form.number;
				} else {
					this.takecash = {
						patientName: '',
						idCard: '',
						prescript_number: '',
						prescription: [],
						shouldMoney: 0,
						exactMoney: 0,
						theChange: 0
					};
				}
			}
		},
		created() {
			//病患信息
			let that = this;
			let apilogin = "http://localhost:8088/getAllPatientList2";
			this.$http.get(apilogin).then((response) => {
				that.patientList = response.body.data.Patient;
				console.log(that.patientList);
			}, response => {
				this.$message({
					message: '数据请求失败',
					type: 'error'
				});
			});
		}
		// watch: {
		// 	number: function() {
		// 		this.takecash.prescript_number = this.number;

		// 		for (let i = 0; i < this.patients.length; i++) {
		// 			if (this.patients[i].number === this.number) {
		// 				this.takecash.prescription = this.patients[i].prescription.drug;
		// 				this.isShow = this.patients[i].number;
		// 				// 暂时写死数据
		// 				this.takecash.shouldMoney = 320;
		// 			}
		// 		}
		// 	}
		// }
	};
</script>

<style>
	.takecash .takecash-title {
		font-weight: bold;
		font-size: 28px;
		width: 50%;
		margin: 0 auto;
		text-align: center;
		padding-bottom: 40px;
	}

	.takecash-ruleForm {
		width: 50%;
		margin: 0 auto;
	}

	.el-form-item {
		width: 100%;
	}

	.el-select {
		width: 100%;
	}

	.takecash_p {
		overflow: hidden;
		padding-left: 30px;
		padding-top: 20px;
	}

	.shouldMoney {
		float: left;
		display: inline-block;
		width: 80%;
		/*top: 325px*/
		/*right: 335px*/
	}

	.theChange {
		float: left;
		width: 81%;
		margin-left: 25px;
		display: inline-block;
	}

	.computeBtn {
		float: left;
		display: inline-block;
	}

	.changeBtn {
		display: inline-block;
		float: left;
		/*top: 460px*/
		/*right: 335px*/
	}

	.exactMoney {
		margin-left: 20px;
		width: 100%;
	}

	.money {
		font-size: 20px;
		color: black;
		font-weight: bold;
	}

	.reset {
		margin-left: 45%;
		margin-top: 50px;
	}
</style>